import MD5 from 'react-native-md5';
import {DeviceEventEmitter} from 'react-native';
import StorageManager, {CHAIN_TYPE} from '../storage';
let basicUrl = undefined;

StorageManager.load(CHAIN_TYPE).then((res) => {
  console.log(res);

  if (!res) {
    basicUrl = require('../config').BASE_API;
  } else {
    basicUrl = require('../config').BASE_API + '/arbitrum';
  }

  if (res === null) {
    StorageManager.save(CHAIN_TYPE, 0);
  }

  console.log('读取的bscicUrl为' + basicUrl);
});

export default class FetchUtils {
  static getChainUrl() {
    return basicUrl;
  }

  static modifyUrl(type) {
    StorageManager.save(CHAIN_TYPE, type);

    if (type == 0) {
      basicUrl = require('../config').BASE_API;
    } else {
      basicUrl = require('../config').BASE_API + '/arbitrum';
    }

    console.log('修改basicUrl' + basicUrl);
  }

  /**
   * fetch timeout
   * @param {Promise} fetchPromise  fetch Request to return the Promise
   * @param {number} [timeout = 30000] In milliseconds, the default timeout is set to 10 seconds
   * @return {Promise}
   */
  static timeoutFetch(fetchPromise, timeout = 30000) {
    let timeoutFn = null;
    const timeoutPromise = new Promise((resolve, reject) => {
      timeoutFn = () => {
        reject('timeout promise');
      };
    });
    const abortablePromise = Promise.race([fetchPromise, timeoutPromise]);
    setTimeout(() => {
      timeoutFn();
    }, timeout);
    return abortablePromise;
  }

  static get(url, params) {
    console.log('查询的url为：' + basicUrl + url);
    console.log(JSON.stringify(params, null, 2));

    if (params) {
      const paramsArray = [];
      Object.keys(params).forEach((key) =>
        paramsArray.push(`${key}=${params[key]}`),
      );
      if (url.search(/\?/) === -1) {
        url += `?${paramsArray.join('&')}`;
      } else {
        url += `&${paramsArray.join('&')}`;
      }
    }
    // const currentTime = new Date().getTime();
    // const sign = MD5.hex_md5(this.getSign(currentTime, url));
    // const signParam = [`time=${currentTime}`, `sign=${sign}`].join('&');
    // if (url.search(/\?/) === -1) {
    //   url += `?${signParam}`;
    // } else {
    //   url += `&${signParam}`;
    // }
    return new Promise((resolve, reject) => {
      this.timeoutFetch(
        fetch(basicUrl + url, {
          method: 'GET',
        }),
      )
        .then((response) => response.json())
        .then((responseJson) => {
          if (responseJson.code == 200) {
            resolve(responseJson);
          } else {
            if (responseJson.code == 406) {
              DeviceEventEmitter.emit('AuthenticationError');
            }
            reject(responseJson);
          }
        })
        .catch((err) => {
          DeviceEventEmitter.emit('netRequestErr', err + '');
          reject(err + '');
        });
    });
  }

  static post(url, params, images, time = 30000) {
    // const currentTime = new Date().getTime();
    // const sign = MD5.hex_md5(this.getSign(currentTime, url));
    // params.sign = sign;
    // params.time = currentTime;
    if (images) {
      const formData = new FormData();
      Object.keys(params).forEach((key) => {
        formData.append(key, params[key]);
      });
      for (let i = 0; i < images.length; i++) {
        const {uri, name} = images[i];
        const timeName = `${params.userToken}_${new Date().getTime()}_${i}.png`;
        const imagefile = {uri, type: 'multipart/form-data', name: timeName};
        console.log(imagefile);
        formData.append(name, imagefile);
      }
      return new Promise((resolve, reject) => {
        this.timeoutFetch(
          fetch(basicUrl + url, {
            method: 'POST',
            body: formData,
          }),
          time || 120000,
        )
          .then((response) => response.json())
          .then((responseJson) => {
            if (responseJson.code == 200) {
              resolve(responseJson);
            } else {
              if (responseJson.code == 406) {
                DeviceEventEmitter.emit('AuthenticationError');
              }
              reject(responseJson);
            }
          })
          .catch((err) => {
            DeviceEventEmitter.emit('netRequestErr', err + '');
            reject(err + '');
          });
      });
    }
    return new Promise((resolve, reject) => {
      this.timeoutFetch(
        fetch(basicUrl + url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8',
          },
          body: JSON.stringify(params),
        }),
        time,
      )
        .then((response) => response.json())
        .then((responseJson) => {
          if (responseJson.code == 200) {
            resolve(responseJson);
          } else {
            if (responseJson.code == 406) {
              DeviceEventEmitter.emit('AuthenticationError');
            } else {
              reject(responseJson);
            }
          }
        })
        .catch((err) => {
          console.log(err);
          DeviceEventEmitter.emit('netRequestErr', err + '');
          reject(err + '');
        });
    });
  }
}
